package com.ybf.api.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.github.pagehelper.PageHelper;
import com.ybf.api.entity.PageRequest;
import com.ybf.api.entity.PageResult;
import com.ybf.api.entity.User;
import com.ybf.api.mapper.UsersMapper;
import com.ybf.api.service.UserService;
import com.ybf.api.utils.EncryptUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("UserService")
public class UserImpl implements UserService {

    @Resource
    private UsersMapper usersMapper;

    @Override
    public User login(String username, String password) {
        String pwd = EncryptUtils.md5(password);
        return usersMapper.findByUsernameAndPassword(username, pwd);
    }

    @Override
    public Boolean logout() {
        StpUtil.logout();
        return StpUtil.isLogin();
    }

    @Override
    public PageResult<User> list(User user, PageRequest pageRequest) {
        PageHelper.startPage(pageRequest);
        List<User> userList = usersMapper.list(user);
        PageResult<User> pageResult = new PageResult<User>(userList);
        return pageResult;
    }

    @Override
    public User info(Integer id) {
        return usersMapper.info(id);
    }

    @Override
    public Boolean delete(Integer id) {
        return usersMapper.delete(id) > 1;
    }

    @Override
    public Integer edit(User user) {
        user.setPassword(EncryptUtils.md5(user.getPassword()));
        if (user.getId() != null) {
            return usersMapper.edit(user);
        }
        return usersMapper.add(user);
    }
}
